package com.slt.android.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

/**
 * Created by dp on 2017/12/14.
 */

public class CustomTextView extends android.support.v7.widget.AppCompatTextView {
    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawShape(canvas);
        super.onDraw(canvas);
        if(mGradientMatrix != null){
            mTranslate += mViewWidth/5;
            if(mTranslate > 2 * mViewWidth){
                mTranslate = -mViewWidth;
            }
            mGradientMatrix.setTranslate(mTranslate , 0);
            mLinearGradient.setLocalMatrix(mGradientMatrix);
            postInvalidateDelayed(200);
        }
        canvas.restore();
    }


    Paint mPaint1 = new Paint();
    Paint mPaint2 = new Paint();
    Paint mPaint3;

    LinearGradient mLinearGradient;
    Matrix mGradientMatrix;
    int mViewWidth;
    int mTranslate;
    private void drawShape(Canvas canvas) {

        mPaint1.setColor(getResources().getColor(android.R.color.black));
        mPaint1.setStyle(Paint.Style.FILL);

        mPaint2.setColor(Color.YELLOW);
        mPaint2.setStyle(Paint.Style.FILL);

        canvas.drawRect( 0 , 0 , getMeasuredWidth() , getMeasuredHeight() , mPaint1);

        canvas.drawRect( 10 , 10 , getMeasuredWidth() -10 , getMeasuredHeight()-10 , mPaint2);
        canvas.save();
        canvas.translate(10 , 0);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if(mViewWidth == 0){
            mViewWidth = getMeasuredWidth();
            if(mViewWidth > 0){
                mPaint3 = getPaint();
                mLinearGradient = new LinearGradient(0 , 0 , mViewWidth , 0 , new int[]{Color.BLUE , 0xffffff , Color.BLUE} , null , Shader.TileMode.CLAMP);
                mPaint3.setShader(mLinearGradient);
                mGradientMatrix = new Matrix();
            }
        }
    }
}
